package com.moli.lumpSugar.user.event.listener;


import com.moli.lumpSugar.common.domain.enums.IdempotentEnum;
import com.moli.lumpSugar.user.dao.UserDao;
import com.moli.lumpSugar.user.domain.entity.User;
import com.moli.lumpSugar.user.domain.enums.ItemEnum;
import com.moli.lumpSugar.user.event.UserRegisterEvent;
import com.moli.lumpSugar.user.service.IUserBackpackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @program: LumpSugarChat
 * @description: 用户注册事件监听者
 * @author: zhangjt
 * @create: 2024-10-25 17:21
 **/
@Component
public class UserRegisterEventListener {
    @Autowired
    private IUserBackpackService userBackpackService;
    @Autowired
    private UserDao userDao;

    @TransactionalEventListener(value = UserRegisterEvent.class, phase = TransactionPhase.BEFORE_COMMIT)
    public void acquireModifyNameCode(UserRegisterEvent userRegisterEvent) {
        User user = userRegisterEvent.getUser();
        userBackpackService.acquireItem(user.getId(), ItemEnum.MODIFY_NAME_CARD.getId(), IdempotentEnum.UID, user.getId().toString());
    }

    @TransactionalEventListener(value = UserRegisterEvent.class, phase = TransactionPhase.BEFORE_COMMIT)
    public void acquireBadges(UserRegisterEvent userRegisterEvent) {
        User user = userRegisterEvent.getUser();
        int registeredCount = userDao.count();
        if (registeredCount < 10) {
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP10_BADGE.getId(), IdempotentEnum.UID, user.getId().toString());
        } else if (registeredCount < 100) {
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP100_BADGE.getId(), IdempotentEnum.UID, user.getId().toString());
        }
    }
}
